<?php

namespace app\common\model;

use think\Exception;
use think\Model;

class UserGoods extends Model
{
    // 表名
    protected $name = 'user_goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text'
    ];
    

    



    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
    
    public function user(){
    	return $this->belongsTo('user', 'user_id', 'id', '', 'left')
		    ->setEagerlyType(0);
    }
	
	public function goods(){
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')
			->setEagerlyType(0);
	}

    public function selectGoods($delIds, $selectIds, $merid, $userId) {
    	$this->startTrans();
    	try {
    		if($delIds) {
    			$delIds = explode(',', $delIds);
    			$delRes = $this
				    ->where(['user_id' => $userId, 'goods_id' => ['in', $delIds]])
				    ->delete();
    			if($delRes === false) {
    				throw new Exception('删除商品出错');
			    }
		    }
		    
		    if($selectIds) {
		    	$selectIds = explode(',', $selectIds);
		    	$insertdata = [];
		    	foreach ($selectIds as $id) {
		    		$insertdata[] = [
		    		    'merid' => $merid,
					    'user_id' => $userId,
					    'goods_id' => $id,
					    'create_time' => time(),
					    'update_time' => time(),
					    'status' => 1
				    ];
			    }
			    
			    $addRes = $this->insertAll($insertdata);
		    	if($addRes === false) {
		    		throw new Exception('添加选择商品出错');
			    }
		    }
    		
    		$this->commit();
    		return true;
	    } catch (Exception $e) {
    		$this->rollback();
    		$this->error = $e->getMessage();
    		return false;
	    }
    }
}
